<template>
  <div class="backup" id="backup">
    <!-- 功能按钮 -->
    <div class="tips">
      操作说明
      <a-tooltip placement="right">
        <template #title>
          <span> 数据备份功能仅支持：mysql 、Oracle、SQL Server3种数据库。</span>
        </template>
        <span class="iconfont icon-hint1"></span>
      </a-tooltip>
    </div>
    <div class="backup_button">
      <a-button class="addButton" type="primary" :disabled="dataBackupAble" @click="addRecord">
        <template #icon>
          <span class="iconfont icon-Add iconadd"></span>
        </template>
        数据备份
      </a-button>
    </div>
    <!-- 表格展示部分 -->
    <baseTable :columns="columns.backupColumns" :dataSource="configData.records" :isSelect="true" :scroll="scroll"
      ref="sensitiveBaseTables" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete"
      :total="configData.total" :rowSelection="1" ele="backup" @changePage="changePage">
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: downloadAble }" @click="downloadtemp(record)">下载 </a>
          <a class="eidtRecords" :class="{ disable: dataRecoverAble }" @click="recoveryBackup(record)">恢复 </a>
          <a class="eidtRecords" :class="{ disable: deleteAble }" @click="confirmDelete(record)">删除 </a>
        </template>
      </template>

    </baseTable>

    <!-- 新建数据备份模态框 -->
    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
      @handleOk="buttonMessage" @handleCancle="isVisible = false" class="sensitive_modal">
      <template v-slot:body>
        <div>
          <a-form name="advanced_search" class="ant-advanced-search-form" autoComplete="off" :model="formState"
            v-if="isVisible">
            <a-form-item :name="['backup', 'value']" :label="formState.backup.label" :rules="[formState.backup.rule]">
              <a-textarea v-model:value="formState.backup.value" show-count :maxlength="255" allow-clear
                :auto-size="{ minRows: 2, maxRows: 5 }" />

            </a-form-item>
          </a-form>
        </div>
      </template>
    </base-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch, nextTick, createVNode, computed } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import columns from "@/components/table/tableConfig/tableColumn/systemTableColumn";
import { getTableScroll, } from "@/components/table/tableConfig/table";
import baseModal from "@/components/modal/baseModal.vue";

import { message } from "ant-design-vue";
import request from "@/api/index";
import { scrollType, modeProp } from "@/type.d";
import globalFun from "@/utils/global";
import {routerPerm} from '@/utils/common';

// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};
interface dataSourceType {
  [propName: string]: any;
}

//data
// 按钮权限
const dataBackupAble = ref<boolean>(false);
const downloadAble = ref<boolean>(false);
const dataRecoverAble = ref<boolean>(false);
const deleteAble = ref<boolean>(false);
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = false; // 是否需要分页器中的自定义全选和删除

//表格数据
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
const sensitiveBaseTables = ref<any>(null); // basetable的ref
const deleteArr = ref<(string | number)[]>([]);

// 模态框数据
const isVisible = ref<boolean>(false);
const modAlProps: modeProp = reactive({
  width: "M",
  title: "数据备份",
});
//模态框button按钮个数和文案修改
const buttons = ref<dataSourceType[]>([
  {
    text: "保存",
    "html-type": "submit",
    keepAlive: true,
  },
]);
const formState = reactive<dataSourceType>({
  backup: {
    value: "",
    rule: {
      required: false,
      validator: '',
      trigger: ["blur"],
      msg1: "",
      msg2: "",
      api: "",
      id: "",
      params: "backup",
    },
    label: "备注",
  },
  id: "",
});

// 当前页和数量
const pageCurrent = ref<number>(1);
const pageSize = ref<number>(10);
//methods
const addRecord = async () => {
  //新加数据备份模态框条件修改
  //添加数据备份数据
  isVisible.value = true;
  formState.backup.value = "";
};
// 新添或编辑数据备份调取接口
const buttonMessage = async (msg: dataSourceType) => {
  //保存
  let params: dataSourceType = {
    remark: formState.backup.value,
  };
  request.addBackup(params)
    .then((res: any) => {
      if (res.code == "00000 00000") {
        getRdecord();
        message.success(res.message);
        isVisible.value = false;
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// 删除单个数据备份
const confirmDelete = async (item: any) => {
  if(deleteAble.value) return
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value);
};
const deleteRecords = async (keys: (string | number)[] = []) => {
  // 调接口删除数据备份
  let data = {
    id: keys[0]
  }
  await request.deleteBackupdata(data).then((res: any) => {
    if (res.code == "00000 00000") {
      message.success(res.message);
      getRdecord({});
    } else {
      message.error(res.message);
    }
  });
};
const getRdecord = async (datas: dataSourceType = {}) => {
  // 获取表格数据
  const data: {} = {
    pageNumber: datas.pageNumber || pageCurrent.value,
    pageSize: datas.pageSize || pageSize.value,
  };
  const telData = (await request.getBackupList(data)) || {};
  configData.total = telData.total;
  configData.size = telData.size;
  configData.records = telData.records;
  sensitiveBaseTables.value.selectedRowKeys = [];
  nextTick(() => {
    let obj = getTableScroll(74, "backup", 80);
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
  });
};
const downloadtemp = async (record: dataSourceType) => {
  if(downloadAble.value) return
  // 下载数据备份
  await request
    .downloadBackup(record.id)
    .then((res: any) => {
      globalFun.downloadFile(res, "下载数据备份文件.gcbak");
    })
    .catch((err: any) => {
      console.log(err, 999129328139218);
      throw new Error(err);
    });
};
const recoveryBackup = async (record: dataSourceType) => {
  if(dataRecoverAble.value) return
  // 恢复数据备份
  await request
    .recoveryBackupData(record.id)
    .then((res: any) => {
      message.success(res.message);
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  let datas: dataSourceType = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  pageCurrent.value = data.pageCurrent;
  pageSize.value = data.pageSize;
  getRdecord(datas);
};

//onmounted
onMounted(async () => {
  routerPerm().includes('dataBackupAble') ? dataBackupAble.value = false : dataBackupAble.value = true;
  routerPerm().includes('downloadAble') ? downloadAble.value = false : downloadAble.value = true;
  routerPerm().includes('dataRecoverAble') ? dataRecoverAble.value = false : dataRecoverAble.value = true;
  routerPerm().includes('deleteAble') ? deleteAble.value = false : deleteAble.value = true;
  getRdecord();
});
</script>
<style lang="scss" scoped>
.backup {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background-color: #fff;
  overflow: hidden;

  .tips {
    margin-bottom: 16px;
    font-size: 14px;
    color: #333;
  }

  .backup_button {
    padding-bottom: 16px;
    display: flex;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

    .searchContent {
      margin-left: auto;
      margin-right: 0px;

      .icon-search {
        font-size: 20px;
        color: rgba(0, 0, 0, 0.45);
        position: absolute;
        right: 12px;
        top: 0px;
      }
    }
  }

  :deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }

  .eidtRecords:nth-last-child(1) {
    margin-right: 0;
  }
}
.disable {
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
}
:deep(.ant-form-item) {
  width: 596px;
  display: flex;

  // margin-left: 28px;
  .ant-form-item-control {
    width: 498px;
    margin-left: 4px;
    flex: unset;
  }

  .ant-form-item-label {
    flex-grow: 0;
    width: 42px;
    text-align: right;
  }
}

::v-deep(.ant-form-item-control-input-content:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}
</style>
<style>
.sensitive_modal .ant-modal-body {
  margin-bottom: -24px;
}
</style>
